<template>
  <div>
    <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="handleAvatarSuccess">
      <img v-if="img" :src="img" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-progress :percentage="percentage"></el-progress>
  </div>
</template>
<script>
import COS from "cos-js-sdk-v5";
//初始化COS储存桶
const cos = new COS({
  SecretId: 'AKIDucI6vdHwUqz5M4Z2TxU2ZAygNxVwJapw',
  SecretKey: 'HNOMQPKBtcCZ6f6MPNHAwddfdkuxrcN4'
})
export default {
  name: 'imgUpload',
  props: {
    img: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imageUrl: '',
      percentage: 0
    }
  },
  created () {
  },
  computed: {
  },
  methods: {
    handleAvatarSuccess (e) {
      const that = this
      cos.putObject({
        Bucket: 'shuai-1318986562', // 存储桶名称
        Region: 'ap-nanjing', // 地域名称
        Key: e.file.name, // 文件名称
        StorageClass: 'STANDARD', // 固定值
        Body: e.file,// 文件对象
        onProgress: function (progressData) {
          that.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
          this.$emit('update:img', `http://${data.Location}`)
        }
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
